import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: {
      title: '首页 - 这部动漫',
      requiresAuth: false
    }
  },
  {
    path: '/rankings',
    name: 'Rankings',
    component: () => import('../views/Rankings.vue'),
    meta: {
      title: '排行榜 - 这部动漫',
      requiresAuth: false
    }
  },
  {
    path: '/all-animes',
    name: 'AllAnimes',
    component: () => import('../views/AllAnimes.vue'),
    meta: {
      title: '全部动漫 - 这部动漫',
      requiresAuth: false
    }
  },
  {
    path: '/nominate',
    name: 'Nominate',
    component: () => import('../views/Nominate.vue'),
    meta: {
      title: '提名 - 这部动漫',
      requiresAuth: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: {
      title: '登录 - 这部动漫',
      requiresAuth: false
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: {
      title: '注册 - 这部动漫',
      requiresAuth: false
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/Profile.vue'),
    meta: {
      title: '个人中心 - 这部动漫',
      requiresAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, _from, next) => {
  // 设置页面标题
  document.title = to.meta.title as string || '这部动漫'
  
  // 检查是否需要登录
  const requiresAuth = to.meta.requiresAuth
  // 更全面地检查登录状态
  const user = localStorage.getItem('user')
  const token = localStorage.getItem('authorization')
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true' && user && token
  
  if (requiresAuth && !isLoggedIn) {
    // 需要登录但未登录，跳转到登录页面
    next({ name: 'Login' })
  } else {
    next()
  }
})

export default router